package com.huizhonglm.diap.core.storage.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.huizhonglm.diap.R;
import com.huizhonglm.diap.core.storage.pref.Preferences;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 加载内置数据库(省份、城市、地区)
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2014-11-25 14:53
 */
public class DistrictDBHelper {
    private static final int CURR_VERSION = 1;

    private String DB_PATH;
    private SQLiteDatabase db;
    private Context mContext;

    public DistrictDBHelper(Context context) {
        mContext = context;
        DB_PATH = context.getFilesDir().getParent() + "/district.db";
        int version = Preferences.getInstance().getInt("district_db_version", 1);
        if (version != CURR_VERSION) {
            File file = new File(DB_PATH);
            if (file.exists()) {
                file.delete();
            }
            Preferences.getInstance().putInt("district_db_version", CURR_VERSION);
        }
    }

    public void openDatabase() {
        db = openDatabase(DB_PATH);
    }

    public SQLiteDatabase getDatabase() {
        return this.db;
    }

    public void closeDatabase() {
        if (db != null) {
            db.close();
        }
    }

    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            File file = new File(dbfile);
            if (!file.exists()) {
                InputStream is = mContext.getResources().openRawResource(R.raw.district);
                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[2048];
                int count;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                    fos.flush();
                }
                fos.close();
                is.close();
            }
            db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
            return db;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}